package com.yx.demo

import android.os.Bundle
import android.view.View
import androidx.databinding.DataBindingUtil
import com.yecontech.qrcode.QRCodeModule
import com.yecontech.qrcode.QRScanException
import com.yecontech.qrcode.ScanCallback
import com.yecontech.qrcode.tty.TtyModule
import com.yx.demo.databinding.ActivityCodeScannerBinding


class CodeScannerActivity : BaseActivity() {

    private lateinit var binding: ActivityCodeScannerBinding
    private lateinit var qrCodeModule: QRCodeModule


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_code_scanner)
        binding.clear.setOnClickListener { binding.textView.text = "" }

        qrCodeModule = TtyModule()
        val bundle = Bundle()
        bundle.putString(QRCodeModule.KEY_NODE, "/dev/ttyS1")
        bundle.putInt(QRCodeModule.KEY_BAUDRATE, 115200)
        bundle.putBoolean("beep", false)
        qrCodeModule.init(context, bundle)

    }

    override fun onResume() {
        super.onResume()
        qrCodeModule.start(object:ScanCallback{
            override fun onOpenSuccess() {

            }

            override fun onOpenError(exception: QRScanException?) {

            }

            override fun onScanResult(code: String?, type: String?) {
                append(code)
            }

        })
    }

    override fun onPause() {
        super.onPause()
        qrCodeModule.stop()
    }

    private fun append(values: String?) {
        handler.post {
            if (binding.textView.length() > 10240) {
                binding.textView.text = ""
            }
            binding.textView.append(values)
            binding.textView.append("\r\n")
            binding.scrollView.fullScroll(View.FOCUS_DOWN)
        }
    }
}